package com.chinda.common.init;

import com.chinda.common.cache.observable.CacheObservable;
import com.chinda.modules.job.entity.ScheduleJobEntity;
import com.chinda.modules.job.service.ScheduleJobService;
import com.chinda.modules.job.utils.ScheduleUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

/**
 * ContextRefresh 之后加载需要初始化数据
 *
 * @author Wang Chinda
 * @date 2021/7/17
 * @see
 * @since 1.0
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class ContextRefreshInitAfterProcess implements ApplicationListener<ContextRefreshedEvent> {

    private final Scheduler scheduler;
    private final ScheduleJobService scheduleJobService;
    private final CacheObservable cacheObservable;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 初始化job
        this.initJob();

        cacheObservable.initCache();
    }

    /**
     * 初始化Job
     */
    private void initJob() {
        log.info("init job start ...");
        List<ScheduleJobEntity> scheduleJobList = scheduleJobService.list();
        for(ScheduleJobEntity scheduleJob : scheduleJobList){
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            // 如果不存在，则创建
            if(cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
        log.info("Successfully init job");
    }

}
